package com.example.elm.Account

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import android.graphics.Color
import androidx.activity.ComponentActivity
import com.example.elm.Public.AccountInfo
import com.example.elm.Public.MyApplication
import com.example.elm.databinding.IntroductionChangeBinding
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.URLEncoder
import kotlin.concurrent.thread

class IntroductionActivity : ComponentActivity() {
    private lateinit var binding: IntroductionChangeBinding
    private val server_ip = MyApplication.serverIp
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = IntroductionChangeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val AccountInformation = CommonUtil.getSerializable(this, "info", AccountInfo::class.java)
        val old = AccountInformation
        val maxLength = 20

        binding.introduction.setText(old.introduction)
        binding.wordCount.setText("${old.introduction.length}/$maxLength")
        binding.back.setOnClickListener {
            val intent = Intent()
            intent.putExtra("info", old)
            setResult(RESULT_OK, intent)
            finish()
        }
        binding.confirm.setOnClickListener {
            val currentText = binding.introduction.text.toString()

            if (AccountInformation.account == ""){
                Toast.makeText(this, "未登录", Toast.LENGTH_SHORT).show()
                binding.introduction.text.clear()
            }
            else if (currentText.length > maxLength) {
                // 显示字数超限提示
                Toast.makeText(this, "字数过多，请控制在 $maxLength 字以内", Toast.LENGTH_SHORT).show()
            }
            else {
                // 更新结果返回到调用 Activity
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show()
                val new = AccountInfo(AccountInformation.account, AccountInformation.password, AccountInformation.name,
                    AccountInformation.people_name, AccountInformation.head_image, currentText)
                update_introduction(new)
                val intent = Intent()
                intent.putExtra("info", new)
                setResult(RESULT_OK, intent)
                finish()
            }
        }

        // 监听简介输入框，动态更新字数统计
        binding.introduction.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val currentLength = s?.length ?: 0
                updateWordCount(currentLength, maxLength)
            }
            override fun afterTextChanged(s: Editable?) {}
        })

    }
    private fun updateWordCount(currentLength: Int, maxLength: Int) {
        val wordCountText = "$currentLength/$maxLength"
        val spannable = SpannableString(wordCountText)

        // 动态设置当前字数颜色
        val color = if (currentLength > maxLength) Color.RED else Color.GRAY
        spannable.setSpan(
            ForegroundColorSpan(color),
            0,
            wordCountText.indexOf("/"),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        // 确保 "/20" 始终为黑色
        binding.wordCount.text = spannable
    }

    //连接服务器，更新简介
    fun update_introduction(info: AccountInfo){
        val jsp = "http://$server_ip:8080/Account/change_Introduction.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val requestBody = FormBody.Builder()
                    .add("phone", URLEncoder.encode(info.account, "UTF-8"))
                    .add("introduction", URLEncoder.encode(info.introduction, "UTF-8"))
                    .build()
                val request: Request = Request.Builder()
                    .url(jsp)
                    .post(requestBody)
                    .build()
            }
            catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
}